package schema

import (
	"sync"
)

type Manager struct {
	cache              ICache
	disableGlobalCache bool

	caches    map[string]ICache
	cacheLock sync.RWMutex
}

func NewManager() *Manager {
	return &Manager{
		caches: make(map[string]ICache),
	}
}

// SetDisableGlobalCache disable global cache or not
func (mgr *Manager) SetDisableGlobalCache(disable bool) {
	if mgr.disableGlobalCache != disable {
		mgr.disableGlobalCache = disable
	}
}

func (mgr *Manager) SetICache(tableName string, cache ICache) {
	mgr.cacheLock.Lock()
	mgr.caches[tableName] = cache
	mgr.cacheLock.Unlock()
}

func (mgr *Manager) GetICache(tableName string) ICache {
	var cacher ICache
	var ok bool
	mgr.cacheLock.RLock()
	cacher, ok = mgr.caches[tableName]
	mgr.cacheLock.RUnlock()
	if !ok && !mgr.disableGlobalCache {
		cacher = mgr.cache
	}
	return cacher
}

// SetDefaultICache set the default cacher. Xorm's default not enable cacher.
func (mgr *Manager) SetDefaultICache(cacher ICache) {
	mgr.cache = cacher
}

// GetDefaultICache returns the default cacher
func (mgr *Manager) GetDefaultICache() ICache {
	return mgr.cache
}

